<?php

namespace app\admin\controller;

use app\admin\model\Notice;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\MoneyLog;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 提现申请
 *
 * @icon fa fa-circle-o
 */
class Withdraw extends Backend
{

    /**
     * Withdraw模型对象
     * @var \app\admin\model\Withdraw
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Withdraw;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("statusArrList", $this->model->getStatusArrList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model->with(['user'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 编辑
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        if($params['status'] == 2){
            if($params['money_ok']<=0){
                $this->error('通过申请时，打款金额需要大于0');
            }
            if($params['money_ok']>$row['money']){
                $this->error('打款金额不得大于提现金额');
            }
            if($params['money_ok'] == $row['money']){
                //全部提现，直接通知
                $send_add_notice = [];
                $send_add_notice['title'] = '全部提现成功通知';//标题
                $send_add_notice['content'] = '您申请的提现'.$params['money_ok'].'元已通过，款已转入您的银行账户，请注意查收！';//内容
                $send_add_notice['need_confirm'] = 2;//是否需要确认 1是 2否
                $send_add_notice['jump'] = '';//跳转地址
                $send_add_notice['teacher_class_id'] = 0;//课程id
                $send_add_notice['teacher_class_dtl_id'] = 0;//课程安排id
                $send_add_notice['send_user_id'] = 0;//发送人id
                $send_add_notice['get_user_id'] = $row['user_id'];//接收人id
                $send_add_notice['identity_type'] = '教师';//接收人身份
                $send_add_notice['addtime'] = date('Y-m-d H:i:s');//添加时间
                $send_add_notice['is_read'] = 1;//是否已读 1未读 2已读
                Notice::insertGetId($send_add_notice);
                // 发送个推消息
                Notice::sendGetuiPush($send_add_notice);
            }else{
                $money_sy = precisionRestore($row['money'],$params['money_ok'],'减法');
                //提现部分，通知部分提现，剩余部分退回
                $send_add_notice = [];
                $send_add_notice['title'] = '部分提现成功通知';//标题
                $send_add_notice['content'] = '您申请的提现'.$row['money'].'元，已有'.$money_sy.'元转入您的银行账户，剩余的退回到钱包，请注意查收！';//内容
                $send_add_notice['need_confirm'] = 2;//是否需要确认 1是 2否
                $send_add_notice['jump'] = '';//跳转地址
                $send_add_notice['teacher_class_id'] = 0;//课程id
                $send_add_notice['teacher_class_dtl_id'] = 0;//课程安排id
                $send_add_notice['send_user_id'] = 0;//发送人id
                $send_add_notice['get_user_id'] = $row['user_id'];//接收人id
                $send_add_notice['identity_type'] = '教师';//接收人身份
                $send_add_notice['addtime'] = date('Y-m-d H:i:s');//添加时间
                $send_add_notice['is_read'] = 1;//是否已读 1未读 2已读
                Notice::insertGetId($send_add_notice);
                // 发送个推消息
                Notice::sendGetuiPush($send_add_notice);

                $teacher = User::where(['id'=>$row['user_id']])->find();
                $all_money = precisionRestore($teacher['money'],$money_sy,'加法');
                $money_log = [];
                $money_log['user_id'] = $row['user_id'];//会员ID
                $money_log['money'] = $money_sy;//变更余额
                $money_log['before'] = $teacher['money'];//变更前余额
                $money_log['after'] = $all_money;//变更后余额
                $money_log['memo'] = '提现退回';//备注
                $money_log['createtime'] = time();//创建时间
                $money_log['order_id'] = $row['id'];//订单id
                MoneyLog::insert($money_log);
                User::where(['id'=>$row['user_id']])->update(['money'=>$all_money]);
            }
        }
        if($params['status'] == 3){
            if($params['money_ok']>0){
                $this->error('驳回申请时，打款金额不可大于0');
            }
            $send_add_notice = [];
            $send_add_notice['title'] = '提现失败通知';//标题
            $send_add_notice['content'] = '您申请的提现'.$row['money'].'元，已被驳回，请咨询管理员后重新提交！';//内容
            $send_add_notice['need_confirm'] = 2;//是否需要确认 1是 2否
            $send_add_notice['jump'] = '';//跳转地址
            $send_add_notice['teacher_class_id'] = 0;//课程id
            $send_add_notice['teacher_class_dtl_id'] = 0;//课程安排id
            $send_add_notice['send_user_id'] = 0;//发送人id
            $send_add_notice['get_user_id'] = $row['user_id'];//接收人id
            $send_add_notice['identity_type'] = '教师';//接收人身份
            $send_add_notice['addtime'] = date('Y-m-d H:i:s');//添加时间
            $send_add_notice['is_read'] = 1;//是否已读 1未读 2已读
            Notice::insertGetId($send_add_notice);
            // 发送个推消息
            Notice::sendGetuiPush($send_add_notice);

            $teacher = User::where(['id'=>$row['user_id']])->find();
            $all_money = precisionRestore($teacher['money'],$row['money'],'加法');
            $money_log = [];
            $money_log['user_id'] = $row['user_id'];//会员ID
            $money_log['money'] = $row['money'];//变更余额
            $money_log['before'] = $teacher['money'];//变更前余额
            $money_log['after'] = $all_money;//变更后余额
            $money_log['memo'] = '提现退回';//备注
            $money_log['createtime'] = time();//创建时间
            $money_log['order_id'] = $row['id'];//订单id
            MoneyLog::insert($money_log);
            User::where(['id'=>$row['user_id']])->update(['money'=>$all_money]);
        }



        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
